<template>
    <div class="main_body">
        <header>
            <a @click="back()" class="back"></a>
            <span v-if="studentId">学生详情</span>
            <span v-if="!studentId">添加学生</span>
            <a @click="addStudent" v-if="canAdd||canEdit" class="add">完成</a>
        </header>
        <div class="select_class">
            <div class="model" @click="$api.clickModel(3)" v-if="!useInfo.tsMenuList[3].voOperate.editObj"></div>
            <div class="main" @click="changePhoto()">
                <div class="flex">
                    <div>头像</div>
                    <div class="red">*</div>
                </div>
                <div @click.stop="$api.showImgDetail(detail.studentPhoto)"><img class="image_wrap" :src="$api.formatterImg(detail.studentPhoto)" /></div>
            </div>
            <div class="main">
                <div class="flex">
                    <div>姓名</div>
                    <div class="red">*</div>
                </div>
                <div><input :disabled="detail.studentId" @change="changeValue" v-model="detail.studentName" /></div>
            </div>
            <div class="main" :class="{noClick:!(canAdd||canEdit)}" @click="selectSchool"  >
                <div class="flex">
                    <div>就读学校</div>
                    <div class="red">*</div>
                </div>
                <div class="flex">
                    <div class="desc1" v-for="(school,index) in detail.rsList" :key="index" v-if="school.isCheck">
                        {{school.schoolName}}
                    </div>
                    <div v-if="canAdd||canEdit" class="more"></div>
                </div>

            </div>
            <div v-if="detail.studentId&&detail.classNames" class="main">
                <div class="flex">
                    <div>班级</div>
                    <div class="red">*</div>
                </div>
                <div class="flex" @click="popupClass=true">
                    <div class="desc1 nolong" >
                        {{detail.classNames.substring(0,detail.classNames.length-1)}}
                    </div>
                    <!-- <div @click="selectClass" class="more"></div> -->
                </div>
            </div>
            <div class="main">
                <div class="flex">
                    <div>性别</div>
                    <div class="red">*</div>
                </div>
                <div class="flex">
                    <div>
                        <mt-radio v-model="detail.sex" @change="changeSex" :options="[{
                            label: '男',
                            value: '0',
                            disabled:!canEdit&&!canAdd,
                          } ,{
                            label: '女',
                            value: '1',
                            disabled:!canEdit&&!canAdd,
                          }]">
                        </mt-radio>
                    </div>
                </div>
            </div>
            <div class="main">
                <div class="flex">
                    <div>手表服务</div>
                    <div class="red">*</div>
                </div>
                <div class="flex">
                    <div>
                        <!-- 手表服务默认置灰,不默认就换回去disabled:!canEdit&&!canAdd, -->
                        <mt-radio v-model="detail.watchService" @change="changeShoubiao" :options="[{
                            label: '是',
                            value: '1',
                            disabled:true,
                            
                          },
                          {
                            label: '否',
                            value: '0',
                            disabled:true,
                            
                          } ]">
                        </mt-radio>
                    </div>
                </div>
            </div>
            <div class="main" v-for="(item,index) in detail.tfList" :key="index">
                <div class="flex">
                    <img slot="icon" v-if="index" @click="DeleteParent(index)" src="../../static/images/other/remove-icon.png" width="30" height="30">
                    <div class="desc1">{{item.parents}}</div>
                    <div class="more" v-if="canAdd||canEdit" @click="openParentPicker(index)"></div>
                    <div v-if="index==0" class="red">*</div>
                </div>
                <div class="flex"><input :readonly="!(canAdd||canEdit)" v-model="item.phone" @change="changeValue" placeholder="请输入电话" /></div>
            </div>
            <div v-if="canAdd||canEdit" class="main ">
                <div @click="addParent()"  class="row flex">
                    <img slot="icon" src="../../static/images/other/add-icon.png" width="30" height="30">
                    <div style="height:30px;line-height:30px;">添加</div>
                </div>
            </div>
            <div class="main">
                <div class="flex">
                    <div>生日</div>
                </div>
                <div @click="openTimePicker()">{{new Date(detail.birthday).Format("yyyy-MM-dd")}}</div>
            </div>
            <div class="main" :class="{noClick:!(canAdd||canEdit)}" @click="openGradePicker" >
                <div class="flex">
                    <div>学校年级</div>
                </div>
                <div class="flex">
                    <div class="desc1" style="text-align:right;">{{detail.schoolGrade}}</div>
                    <div v-if="canAdd||canEdit" class="more"></div>
                </div>
            </div>
            <div class="main">
                <div class="flex">
                    <div>学校班级</div>
                </div>
                <div class="flex"><input :readonly="!(canAdd||canEdit)" v-model="detail.schoolClass" @change="changeValue" placeholder="请输入学校班级" /></div>
            </div>
            <div class="main">
                <div class="flex">
                    <div>家庭地址</div>
                </div>
                <div class="flex"><input :readonly="!(canAdd||canEdit)" v-model="detail.address" @change="changeValue" placeholder="请输入家庭地址" /></div>
            </div>
            <div class="main " style="padding-bottom:0;border-bottom:0;">
                <div class="flex">
                    <div>注意事项</div>
                </div>
            </div>
            <div class="main ">
                <div class="textarea_wrap" style="width:100%;padding:0;">
                    <textarea :readonly="!(canAdd||canEdit)" @change="changeValue" v-model="detail.careThing" rows="4"></textarea>
                </div>
            </div>
            <div class="row" v-if="detail.studentId&&useInfo.tsMenuList[3].voOperate.removeObj" @click="deleteStudent" style="padding:0 0.37333rem">
                <mt-button style="width:100%;" type="danger">删除</mt-button>
            </div>
            <div class="row" v-if="canAdd" @click="addStudent" style="padding:0.37333rem;">
                <mt-button style="width:100%;" type="primary">完成</mt-button>
            </div>
            <mt-datetime-picker v-model='birthday' ref="beginDate" :startDate="startDate" type="date" @confirm="changebirthday">
            </mt-datetime-picker>
            <!-- <mt-datetime-picker v-model='entryTime' ref="endDate" :startDate="startDate" type="date" @confirm="changeentryTime" >
            </mt-datetime-picker> -->
            <!-- 选择学历弹窗 -->
            <mt-popup style="background:white;width:100%;" v-model="popupParent" position="bottom">
                <div class="picker-toolbar" style="border-bottom:1px solid #f2f2f2">
                    <span @click="SureOrCanelChangeParent(1)" class="mint-datetime-action mint-datetime-cancel">取消</span>
                    <span @click="SureOrCanelChangeParent()" class="mint-datetime-action mint-datetime-confirm">确定</span>
                </div>
                <mt-picker :slots="slots" @change="ChangeParent"></mt-picker>
                <input class="picker_input" v-model="otherParent" v-if="this.parent =='自定义'">
            </mt-popup>
            <!-- 选择学生类型弹窗 -->
            <mt-popup style="background:white;width:100%;" v-model="popupGrade" position="bottom">
                <div class="picker-toolbar" style="border-bottom:1px solid #f2f2f2">
                    <span @click="SureOrCanelChangeGrade(1)" class="mint-datetime-action mint-datetime-cancel">取消</span>
                    <span @click="SureOrCanelChangeGrade()" class="mint-datetime-action mint-datetime-confirm">确定</span>
                </div>
                <mt-picker :slots="slots2" @change="ChangeGrade"></mt-picker>

            </mt-popup>
            <mt-popup v-model="popupClass" style="position:absolute;padding:0.343rem;" class="popup_center" position="center" popup-transition="popup-fade">
                    {{detail.classNames.substring(0,detail.classNames.length-1)}}
            </mt-popup>
        </div>

        <getImage v-model='sheetVisible'></getImage>
    </div>
</template>

<script>
    import {
        MessageBox
    } from "mint-ui";
    import getImage from "../components/getImage.vue";
    export default {
        data() {
            return {
                slots: [{
                    flex: 1,
                    values: ["爸爸", "妈妈", "爷爷", "奶奶", "其他", "自定义"],
                    className: "slot1",
                    textAlign: "center"
                }],
                slots2: [{
                    values: ["一年级", "二年级", "三年级", "四年级", "五年级", "六年级"],
                    className: "slot2",
                    textAlign: "center"
                }],
                type: false, //判断新增或者编辑
                careThing: "",
                otherParent: "", //用于保存其他家长
                startDate: new Date(null),
                parent: "", //用来缓存选中的家长
                popupParent: false,
                popupGrade: false,
                popupClass: false,
                sheetVisible: false,
                useInfo: {},
                parentPickerIndex: 0, //存储打开家长选择器的下标
                studentId: null,
                education: "", //缓存学历
                Grade: "", //缓存的职务
                birthday: '2010-01-01', //过度时间
                entryTime: null, //过度时间
                detail: {
                    classPhoto: null,
                    birthday: '2010-01-01',
                    entryTime: null,
                    Grade: "",
                    careThing: "",
                    sex: "0",
                    watchService: "0",
                    classIds: "",
                    classNames: "",
                    removeUserIds: "",
                    tfList: [],
                    rsList: []
                }
            };
        },
        components: {
            getImage
        },
        methods: {
            //
            addParent() {
                //新增家长
                this.detail.tfList.push({
                    parents: "",
                    phone: "",
                    userId: this.useInfo.userId
                });
                console.log(JSON.parse(JSON.stringify(this.detail.tfList)));
            },
            back() {
                // this.$api.clearItem();
                this.$api.goBack();
            },
            DeleteParent(index) {
                //删除家长
                if (this.detail.tfList.userId) {
                    this.detail.removeUserIds +=
                        this.detail.removeUserIds + this.detail.tfList.userId;
                }
                this.detail.tfList.splice(index, 1);
                this.beginAddOrEdit();
            },
            selectMainTeacher() {
                //选择主要学生
                sessionStorage.setItem("RadioTitle", "selectMainTeacher");
                this.$router.push({
                    path: "selectTeacher"
                });
            },
            changeSex(newValue) {
                this.detail.sex = newValue;
                this.beginAddOrEdit();
            },
            changeValue() {
                this.beginAddOrEdit();
            },
            changeShoubiao(val) {
                //勾选取消手表服务的时候
                console.log(val);
                if (this.detail.isPay && val == "0") {
                    MessageBox.confirm("该押金已交，是否取消手表服务?")
                        .then(action => {
                            this.detail.watchService = "0";
                            this.beginAddOrEdit();
                        })
                        .catch(e => {
                            this.detail.watchService = "1";
                        });
                } else if (!this.detail.isPay && val == "1") {
                    MessageBox.confirm("该押金未交，是否选中手表服务？")
                        .then(action => {
                            //是
                            this.detail.watchService = "1";
                            this.beginAddOrEdit();
                        })
                        .catch(e => {
                            //否
                            this.detail.watchService = "0";
                        });
                }
            },
            selectSchool() {
                //选择学校
                var list = this.detail.rsList.map(e => {
                    e.radioName = e.schoolName;
                    e.checked = e.isCheck;
                    return e;
                });
                var radioOptions = {
                    title: "周边学校",
                    list
                };
                sessionStorage.setItem("radioOptions", JSON.stringify(radioOptions));
                this.$router.push({
                    path: "radio"
                });
            },
            selectClass() {
                //选择班级
                var array = this.detail.classIds.split(",");
                var list = this.detail.claList.map(e => {
                    e.radioName = e.className;
                    e.radioContent = e.mainTeacherName;
                    e.checked = false;
                    array.forEach(element => {
                        if (e.classId == element) {
                            e.checked = true;
                        }
                    });
                    return e;
                });
                var radioOptions = {
                    title: "选择班级",
                    multiple: true, //允许多选
                    list
                };
                sessionStorage.setItem("radioOptions", JSON.stringify(radioOptions));
                this.$router.push({
                    path: "radio"
                });
            },
            changebirthday() {
                //改变生日
                this.detail.birthday = this.birthday;
                this.beginAddOrEdit();
            },
            changeentryTime() {
                //改变开始时间
                this.detail.entryTime = this.entryTime;
                this.beginAddOrEdit();
            },
            selectAideTeacher() {
                //选择助教老师
                sessionStorage.setItem("RadioTitle", "selectAideTeacher");
                this.$router.push({
                    path: "selectTeacher"
                });
            },
            ChangeGradeName(e, value) {
                this.beginAddOrEdit();
            },
            getRadioBack() {
                //获取选择的学校
                var radioBackOptions = JSON.parse(
                    sessionStorage.getItem("radioBackOptions")
                );
                if (radioBackOptions) {
                    switch (radioBackOptions.title) {
                        case "周边学校":
                            this.detail.rsList = this.detail.rsList.map(element => {
                                if (
                                    element.regionSchoolId == radioBackOptions.item.regionSchoolId
                                ) {
                                    element.isCheck = true;
                                    this.detail.schoolDataId = element.regionSchoolId;
                                } else {
                                    element.isCheck = false;
                                }
                                return element;
                            });
                            break;
                        case "选择班级":
                            this.detail.classIds = "";
                            this.detail.classNames = "";
                            radioBackOptions.item.forEach((element, index) => {
                                this.detail.classIds =
                                    this.detail.classIds + element.classId + ",";

                                if (index == length - 1) {
                                    this.detail.classNames += element.className;
                                } else {
                                    this.detail.classNames += element.className + ",";
                                }

                                this.detail.claList = this.detail.claList.map(cla => {
                                    if (cla.classId == element.classId) {
                                        cla.isCheck = true;
                                    }
                                    return cla;
                                });
                            });
                            break;
                    }
                }
                sessionStorage.removeItem("radioBackOptions");
                this.beginAddOrEdit();
            },
            deleteStudent() {
                //删除学生
                MessageBox.confirm("确定要删除学生吗?").then(action => {
                    var url = "/student/remove";
                    var params = {
                        studentId: this.detail.studentId
                    };
                    this.$api.post(url, params, data => {
                        MessageBox("提示", "删除成功");
                        this.$api.goBack();
                    });
                });
            },
            addStudent() {
                //校验参数,确认无误执行 addOrEdit
                console.log(JSON.parse(JSON.stringify(this.detail)));
                if (!this.detail.studentPhoto) {
                    //如果没有图标
                    MessageBox("提示", "请选择头像");
                    return false;
                }
                if (!this.$check.empty(this.detail.studentName, "请输入学生名称")) {
                    return false;
                }
                if (!this.$check.empty(this.detail.schoolDataId, "请选择就读学校")) {
                    return false;
                }
                // if (!this.$check.empty(this.detail.classIds, "请选择班级")) {
                //     return false;
                // }
                if (!this.checkTfList()) {
                    return;
                }
                // if (!this.$check.phone(this.detail.teacherPhone)) { //验证电话号码
                //     return false;
                // };
                this.addOrEdit();
            },
            beginAddOrEdit() {
                //用来缓存数据
                sessionStorage.setItem("studentDetail", JSON.stringify(this.detail));

                // if (this.detail.studentId) { //有studentId说明是编辑,直接进入编辑
                //     this.addOrEdit();
                // } else {

                // }
            },
            addOrEdit() {
                //新增或者编辑学生
                var params = JSON.parse(JSON.stringify(this.detail));
                params.schoolId = this.useInfo.schoolId;
                params.parents = JSON.stringify(params.tfList);
                delete params.rsList;
                var url = "/student/save";
                params.birthday = new Date(params.birthday).Format("yyyy-MM-dd");
                this.$api.post(url, params, data => {
                    MessageBox("提示", "操作成功");
                    this.$api.removeCookie("studentDetail");
                    this.$api.goBack();
                });
            },
            openTimePicker(end) {
                //打开时间选择器
                if (!this.canAdd || !this.canEdit) {
                    return;
                }
                if (end) {
                    this.$refs.endDate.open();
                } else {
                    this.$refs.beginDate.open();
                }
            },
            checkTfList() {
                var parents = true;
                var phone = true;
                this.detail.tfList.forEach(element => {
                    if (!this.$check.empty(element.parents, "请选择家长称谓")) {
                        parents = false;
                    }
                    if (!this.$check.phone(element.phone)) {
                        phone = false;
                    }
                });
                if (parents && phone) {
                    return true;
                } else {
                    return false;
                }
            },
            openParentPicker(index) {
                this.parentPickerIndex = index;
                this.popupParent = true;
            },
            openGradePicker() {
                this.popupGrade = true;
            },
            SureOrCanelChangeParent(cancel) {
                //家长选择选择器 确定取消点击事件
                console.log(this.parent);
                if (!cancel) {
                    if (this.parent == "自定义") {
                        this.detail.tfList[this.parentPickerIndex].parents = this.otherParent;
                    } else {
                        this.detail.tfList[this.parentPickerIndex].parents = this.parent;
                    }
                    this.beginAddOrEdit();
                }
                this.popupParent = false;
            },
            SureOrCanelChangeGrade(cancel) {
                //学生类型选择器 确定取消点击事件
                if (!cancel) {
                    console.log(this.Grade);
                    this.detail.schoolGrade = this.Grade;
                    this.beginAddOrEdit();
                }
                this.popupGrade = false;
            },
            ChangeParent(picker, values) {
                //选择学期
                this.parent = values[0];
            },
            ChangeGrade(picker, values) {
                //选择职务
                this.Grade = values[0];
            },
            changePhoto() {
                if (!this.canAdd && !this.canEdit) return;
                this.sheetVisible = true;
            },
            getUseInfo() {
                this.useInfo = JSON.parse(sessionStorage.getItem("useInfo"));
                this.studentId = sessionStorage.getItem("studentId");
                this.canAdd = this.useInfo.tsMenuList[3].voOperate.addObj && !this.studentId;
                this.canEdit = this.useInfo.tsMenuList[3].voOperate.editObj;
            },
            getDetail() {
                let detail = JSON.parse(sessionStorage.getItem("studentDetail"));
                if (detail) {
                    //如果有缓存信息,直接用缓存信息就好了,不用获取数据了
                    this.detail = detail;
                    console.log(JSON.parse(JSON.stringify(detail)));
                    this.getImageBack();
                    this.getRadioBack();
                    return;
                }
                if (!this.studentId) {
                    this.studentId = 0;
                }
                console.log(1234);
                var url = "/student/find";
                var params = {
                    studentId: this.studentId,
                    schoolId: this.useInfo.schoolId
                };
                this.$api.post(url, params, data => {
                    var detail = JSON.parse(JSON.stringify(data));
                    console.log("data", JSON.parse(JSON.stringify(detail)));
                    if (this.studentId) {
                        detail = data.info.student;
                        detail.tfList = data.info.tfList;
                        detail.sex = detail.sex.toString();
                        if (detail.watchService) {
                            detail.watchService = detail.watchService.toString();
                        }

                        detail.classNames = data.info.classNames;
                        detail.classIds = data.info.classIds;
                    } else {
                        detail.tfList.push({
                            parents: "爸爸",
                            phone: "",
                            userId: this.useInfo.userId
                        });
                    }

                    detail.claList = data.info.claList;
                    detail.rsList = data.info.rsList;

                    detail.isPay = data.info.isPay;
                    console.log("data", JSON.parse(JSON.stringify(detail)));
                    detail.birthday = new Date(detail.birthday);
                    this.detail = detail;
                    this.getImageBack();
                    this.getRadioBack();
                });
            },
            formatPayPattern(type) {
                //格式化缴费模式
                if (type == 1) {
                    return "按期缴费";
                } else if (type == 2) {
                    return "按月缴费";
                }
            },
            getImageBack() {
                var filepath = JSON.parse(sessionStorage.getItem("imgOption"));
                if (filepath) {
                    this.detail.studentPhoto = filepath.filePath;
                    this.detail.baseFileId = filepath.baseFileId;
                }
                this.$api.removeCookie("imgOption");
                this.beginAddOrEdit();
            }
        },
        created() {
            this.getUseInfo();
            this.getDetail();
        }
    };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    .main_body {
        background: white;
        height: 100%;
    }
    /* .row {
        display: flex;
        padding: 0.4rem 0.5rem;
        font-size: 16px;
    } */
</style>